package com.sise.aio和bio和nio.nio.nioServerClient;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 通道管理器
 *
 * @Author idea
 * @Date 2020-04-12
 */
public class NioClient {

    /**
     * 每个通道都会有一个对应的selector
     */
    private Selector selector;

    /**
     * 程序测试
     *
     * @param args
     * @throws IOException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, InterruptedException {
            NioClient nioClient = new NioClient();
            nioClient.initClient("127.0.0.1",9090);
            nioClient.doConnect();
            Thread.sleep(3000);
    }


    /**
     * 初始化客户端链接
     *
     * @param ip
     * @param port
     * @throws IOException
     */
    public void initClient(String ip, int port) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        this.selector = Selector.open();
        socketChannel.connect(new InetSocketAddress(ip, port));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
    }

    /**
     * 轮训进行链接处理
     */
    public void doConnect() throws IOException {
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isConnectable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    if (socketChannel.isConnectionPending()) {
                        socketChannel.finishConnect();
                    }
                    socketChannel.configureBlocking(false);
                    ByteBuffer byteBuffer = ByteBuffer.wrap("helloworld".getBytes());
                    socketChannel.write(byteBuffer);
                    socketChannel.register(this.selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    this.read(key);
                }
            }
        }
    }


    /**
     * 读取数据信息
     *
     * @param selectionKey
     * @throws IOException
     */
    public void read(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int len = socketChannel.read(byteBuffer);
        if (len != -1) {
            System.out.println("客户端接收信息：" + new String(byteBuffer.array(), 0, len));
        }
    }


}
